﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;

namespace comm
{
    public partial class coms : Form
    {
        // SerialPort serialport = new SerialPort();  
        private System.Collections.ArrayList BytesBuffer = new System.Collections.ArrayList(); //定义一个缓存
        public coms()
        {
            InitializeComponent();

        }

        protected void getcomname() //遍历本机com口
        {
            string[] portNames = SerialPort.GetPortNames();
            for (int i = 0; i < portNames.Length - 1; i++)
            {
                this.comboBox1.Items.Add(portNames[i]);
                comboBox1.SelectedIndex = 0;
            }
            this.comboBox1.Items.Add(this.serialPort1.PortName);
        }

        private void button1_Click(object sender, EventArgs e) //发送数据到串口
        {
            if (this.serialPort1.IsOpen)
            {
                this.serialPort1.Close();
            }
            // try
            //  {
            this.serialPort1.PortName = comboBox1.SelectedItem.ToString();
            this.serialPort1.Open();

            serialPort1.BaudRate = 9600;
            serialPort1.DataBits = 8;
            serialPort1.StopBits = StopBits.One;
            StringToByte(serialPort1, "26030003000232DC");
            //this.textBox1.BeginInvoke(new myDelegate(updateTextBox));
            //this.serialPort1.Close();
            // }
            //catch
            //{
            //     MessageBox.Show(e.ToString());
            //return;
            // }





        }




        #region 字符转为16进制byte并发送，接口为串口、传感器地址
        private void StringToByte(SerialPort serialPort, string address)
        {
            byte[] ByteOut;
            try
            {
                string[] ByteStrings = new string[address.Length / 2];
                int j = 0;
                for (int i = 0; i < ByteStrings.Length; i++)
                {
                    ByteStrings[i] = address.Substring(j, 2);
                    j += 2;
                }
                ByteOut = new byte[ByteStrings.Length];
                for (int i = 0; i <= ByteStrings.Length - 1; i++)
                {
                    ByteOut[i] = byte.Parse(ByteStrings[i], System.Globalization.NumberStyles.HexNumber);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            string str = System.Text.Encoding.Default.GetString(ByteOut);
            serialPort.Write(ByteOut, 0, ByteOut.Length);
        }
        #endregion

        #region byte[] 转成原16进制格式的string
        public static string ToHexString(byte[] bytes) // 0xae00cf => "AE00CF "
        {
            string hexString = string.Empty;
            if (bytes != null)
            {
                StringBuilder strB = new StringBuilder();

                for (int i = 0; i < bytes.Length; i++)
                {
                    strB.Append(bytes[i].ToString("X2"));
                }
                hexString = strB.ToString();
            }
            return hexString;
        }
        #endregion


        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            Thread.Sleep(2000);
            this.textBox1.BeginInvoke(new myDelegate(updateTextBox));
        }

        public delegate void myDelegate();

        public void updateTextBox()
        {
            byte firstByte = Convert.ToByte(serialPort1.ReadByte());
            int bytesRead = this.serialPort1.BytesToRead;
            byte[] bytesData = new byte[bytesRead + 1];
            bytesData[0] = firstByte;
            for (int i = 1; i <= bytesRead; i++)
                bytesData[i] = Convert.ToByte(serialPort1.ReadByte());
            try
            {

                string kkk = ToHexString(bytesData) + "0000";
                string temperature = (Convert.ToDouble(Convert.ToInt32(kkk.Substring(6, 4), 16)) / 10).ToString(); //获得温度
                string shidu = Convert.ToInt32(kkk.Substring(12, 2), 16).ToString(); //获得湿度
                string address = Convert.ToInt32(kkk.Substring(0, 2), 16).ToString(); //获得地址
                string addr = "";
                if (address.Length < 2)
                {
                    addr = "0" + address;
                }
                else
                {
                    addr = address;

                }
                //if (Convert.ToDouble(temperature) < 100 && Convert.ToInt32(shidu) < 99)
                //{
                //    //-----数据写入数据库
                //    //mbl.SensorID = Convert.ToInt32(address);
                //    //mbl.Temperature = temperature;
                //    //mbl.Humidity = shidu;
                //    //bl.Add(mbl);
                //    //---------

                //    //double sz = Convert.ToDouble(temperature); //实时温度
                //    //DataTable errdata = blalarm.GetList("SensorAddress='" + address + "'").Tables[0];
                //    //double js = Convert.ToDouble(errdata.Rows[0]["TemperatureHigh"].ToString());//设置温度
                //    //if (sz > js)
                //    //{
                //    //    if (!blex.ExistsExcessive(address))
                //    //    {
                //    //        mlex.SensorID = address;
                //    //        blex.Add(mlex);
                //    //    }
                //    //}

                string list1 = "地址：" + addr + " |温度：" + temperature + " |湿度：" + shidu + "%" + "  | 时间：" + System.DateTime.Now + Environment.NewLine + Environment.NewLine;
                this.textBox1.AppendText(list1);
                this.textBox1.ScrollToCaret();
                //}
            }
            catch
            { }

        }






        private void coms_Load(object sender, EventArgs e)
        {
            getcomname();
        }



    }
}
